# coding:utf-8
from __future__ import unicode_literals
from django.db import models
from markdown import markdown
from encryption import encryption as make_pwd
# Create your models here.


class Category(models.Model):
    '''标签'''
    title = models.CharField(verbose_name='Title', max_length=255)

    class Meta:
        app_label = 'blog'
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
        ordering = ['title', ]

    def __unicode__(self):
        return self.title


class Comments(models.Model):
    '''评论'''
    user_name = models.CharField('评论者名字', max_length=100)
    text = models.TextField('评论内容', max_length=500)
    date_publish = models.DateField('评论发表时间', auto_now_add=True)
    article = models.ForeignKey('Article', verbose_name='评论所属文章', on_delete=models.CASCADE)

    def __unicode__(self):
        return self.text[:10]


class Article(models.Model):
    '''文章'''
    title = models.CharField(verbose_name='Title', max_length=255)
    content_markdown = models.TextField(verbose_name='Content(Markdown)')
    content_markup = models.TextField(verbose_name='Content(Markup)')
    categories = models.ManyToManyField(Category, verbose_name='Categories', blank=True)
    date_publish = models.DateField(verbose_name='Pulish Date', auto_now_add=True)
    read_num = models.IntegerField(verbose_name='Reading', default=0)

    class Meta:
        app_label = 'blog'
        verbose_name = 'Article'
        verbose_name_plural = 'Articles'
        ordering = ['-date_publish']

    def save(self):
        self.content_markup = markdown(self.content_markdown, ['codehilite'])
        super(Article, self).save()

    def __unicode__(self):
        return self.title


class Visitors(models.Model):
    '''用户'''
    user_name = models.CharField(verbose_name='username', max_length=20)
    password = models.CharField(verbose_name='password', max_length=50)
    user_email = models.EmailField(null=True)
    comments = models.ForeignKey(Comments, null=True)
    head_image = models.ImageField(upload_to='img/', null=True)

    def save(self):
        self.password = make_pwd(self.password)
        super(Visitors, self).save()

    def __unicode__(self):
        return self.user_name
